package com.mg.dubbo.register.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Workbook;

import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.druid.DruidPlugin;
import com.mg.dubbo.register.service.PoiService;
import com.mg.util.ExcelUtil;

public class PoiServiceImpl implements PoiService{

	@Override
	public void loadTableForXls(String sql, com.alibaba.fastjson.JSONObject json) {
		Map<String,Object> map = new HashMap<String,Object>();  
        //连接数据库
        DruidPlugin ds = new DruidPlugin(json.getString("url"), 
        		json.getString("username"),
        		json.getString("password"),
        		json.getString("driverClass"));
        ds.start();
        if(DbKit.getConfig("main")==null){
        	DbKit.addConfig(new Config("main", ds.getDataSource()));
        }
        DbKit.addConfig(new Config("from", ds.getDataSource()));
        List<String> headList = new ArrayList<String>();//表头数据  
        Record r = Db.use("from").findFirst(sql);
        for(String colName : r.getColumnNames()){
        	headList.add(colName);
        }
        List<Record> list = Db.use("from").find(sql);
        ds.stop();
        DbKit.removeConfig("from");
        map.put(ExcelUtil.HEADERINFO, headList);  
        map.put(ExcelUtil.DATAINFON, list);
        Workbook wb;
		try {
			wb = ExcelUtil.getWorkBook(map);
			String filepath = json.getString("filepath");
		    File file = new File(filepath);  
            OutputStream os = new FileOutputStream(file);  
            os.flush();  
            wb.write(os);  
            os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       
	}

}
